package com.dalei.vds;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import com.dalei.vds.settings.DeviceSettings;
import com.dalei.vds.soap.RegisterDeviceSoapImpl;
import com.dalei.vds.telephone.Device;
import com.dalei.vds.telephone.OperatingSystem;
import com.dalei.vds.telephone.net.WifiConnection;
import com.dalei.vdserver.shared.model.ErrorCode;
import com.dalei.vdserver.shared.soap.RegisterDeviceSoap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterDeviceActivity extends Activity {

	private static final String DEVICE_STATUS = "deviceStatus";

	private static final String DEVICE_ID = "deviceId";

	private static final String MODEL = "model";

	private static final String IMEI = "imei";

	private static final String IMEI_SV = "imeiSv";

	private static final String SERIAL_NO = "serialNo";

	private static final String WLAN_MAC = "wlanMac";

	private static final String OS_VERSION = "osVersion";

	private static final int MESSAGE_SHOW_DIALOG = 0x00000000;

	private static final int MESSAGE_DISMISS_DIALOG = 0x00000001;

	private static final int MESSAGE_SHOW_TOAST = 0x00000002;

	private static final int MESSAGE_LOAD_STATUS = 0x00000003;

	private static final int MESSAGE_ENABLE_REGISTRATION = 0x00000004;

	private static final int MESSAGE_DISABLE_REGISTRATION = 0x00000005;

	private TextView statusText;

	private TextView idText;

	private TextView modelText;

	private TextView imeiText;

	private TextView imeiSvText;

	private TextView serialNoText;

	private TextView wlanMacText;

	private TextView osVersionText;

	private ProgressDialog dialog;

	private Button registerBtn;

	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registerdevice);

		handler = new IncomingHandler(this);

		statusText = (TextView) findViewById(R.id.registerdevice_status);

		idText = (TextView) findViewById(R.id.registerdevice_id);

		modelText = (TextView) findViewById(R.id.registerdevice_model);

		imeiText = (TextView) findViewById(R.id.registerdevice_imei);

		imeiSvText = (TextView) findViewById(R.id.registerdevice_imei_sv);

		serialNoText = (TextView) findViewById(R.id.registerdevice_serial_no);

		wlanMacText = (TextView) findViewById(R.id.registerdevice_wlan_mac);

		osVersionText = (TextView) findViewById(R.id.registerdevice_os_version);

		registerBtn = (Button) findViewById(R.id.registerdevice_register);
		registerBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Thread t = new RegisterThread(RegisterDeviceActivity.this);
				t.start();
			}
		});

		Thread thread = new OnLoadThread(this);
		thread.start();
	}

	private static class IncomingHandler extends Handler {

		private WeakReference<RegisterDeviceActivity> reference;

		public IncomingHandler(RegisterDeviceActivity activity) {
			// TODO Auto-generated constructor stub
			reference = new WeakReference<RegisterDeviceActivity>(activity);
		}

		@Override
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			// super.handleMessage(msg);
			RegisterDeviceActivity activity = reference.get();
			switch (msg.what) {
			case MESSAGE_SHOW_DIALOG:
				activity.dialog = ProgressDialog.show(activity, null,
						activity.getString(R.string.waitting));
				break;

			case MESSAGE_DISMISS_DIALOG:
				activity.dialog.dismiss();
				break;

			case MESSAGE_SHOW_TOAST:
				Toast.makeText(activity, activity.getText(msg.arg1),
						Toast.LENGTH_SHORT).show();
				break;

			case MESSAGE_LOAD_STATUS:
				if (msg.obj instanceof Map) {
					Map<String, String> data = (Map<String, String>) msg.obj;
					String deviceStatus = data.get(DEVICE_STATUS);
					if (deviceStatus != null) {
						activity.statusText.setText(deviceStatus);
					} else {
						activity.statusText.setText(activity
								.getString(R.string.unregistered));
					}
					String deviceId = data.get(DEVICE_ID);
					if (deviceId != null) {
						activity.idText.setText(deviceId);
					} else {
						activity.idText.setText(activity
								.getString(R.string.not_available));
					}
					String model = data.get(MODEL);
					if (model != null) {
						activity.modelText.setText(model);
					} else {
						activity.modelText.setText(activity
								.getString(R.string.not_available));
					}
					String imei = data.get(IMEI);
					if (imei != null) {
						activity.imeiText.setText(imei);
					} else {
						activity.imeiText.setText(activity
								.getString(R.string.not_available));
					}
					String imeiSv = data.get(IMEI_SV);
					if (imeiSv != null) {
						activity.imeiSvText.setText(imeiSv);
					} else {
						activity.imeiSvText.setText(activity
								.getString(R.string.not_available));
					}
					String serialNo = data.get(SERIAL_NO);
					if (serialNo != null) {
						activity.serialNoText.setText(serialNo);
					} else {
						activity.serialNoText.setText(activity
								.getString(R.string.not_available));
					}
					String wlanMac = data.get(WLAN_MAC);
					if (wlanMac != null) {
						activity.wlanMacText.setText(wlanMac);
					} else {
						activity.wlanMacText.setText(activity
								.getString(R.string.not_available));
					}
					String osVersion = data.get(OS_VERSION);
					if (osVersion != null) {
						activity.osVersionText.setText(osVersion);
					} else {
						activity.osVersionText.setText(activity
								.getString(R.string.not_available));
					}
				} else {
					Toast.makeText(activity,
							activity.getString(R.string.unknow_error),
							Toast.LENGTH_SHORT).show();
				}
				break;

			case MESSAGE_ENABLE_REGISTRATION:
				activity.registerBtn.setEnabled(true);
				break;

			case MESSAGE_DISABLE_REGISTRATION:
				activity.registerBtn.setEnabled(false);
				break;

			default:
				break;
			}
		}
	}

	private class OnLoadThread extends Thread {

		private Context context;

		public OnLoadThread(Context context) {
			// TODO Auto-generated constructor stub
			this.context = context;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			// super.run();
			handler.sendEmptyMessage(MESSAGE_SHOW_DIALOG);

			Device device = new Device(context);
			String model = device.getModel();
			String imei = device.getIMEI();
			String imeiSv = device.getIMEISV();
			String serialNo = device.getSerialNumber();

			WifiConnection wifi = new WifiConnection(context);
			String wlanMac = wifi.getMacAddress();

			OperatingSystem os = new OperatingSystem();
			String osVersion = os.getVersion();

			RegisterDeviceSoap soap = new RegisterDeviceSoapImpl(context);
			int id = soap.containsDevice(imei);
			String deviceStatus = null;
			String deviceId = null;
			boolean registrable = false;
			if (id > 0) {
				deviceStatus = getString(R.string.registered);
				deviceId = Integer.toString(id);
				registrable = false;
			} else {
				deviceStatus = getString(R.string.unregistered);
				deviceId = getString(R.string.not_available);
				registrable = true;
			}

			Map<String, String> data = new HashMap<String, String>();
			data.put(DEVICE_STATUS, deviceStatus);
			data.put(DEVICE_ID, deviceId);
			data.put(MODEL, model);
			data.put(IMEI, imei);
			data.put(IMEI_SV, imeiSv);
			data.put(SERIAL_NO, serialNo);
			data.put(WLAN_MAC, wlanMac);
			data.put(OS_VERSION, osVersion);

			handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);

			Message msg = handler.obtainMessage();
			msg.what = MESSAGE_LOAD_STATUS;
			msg.obj = data;
			handler.sendMessage(msg);

			if (registrable) {
				handler.sendEmptyMessage(MESSAGE_ENABLE_REGISTRATION);
			} else {
				handler.sendEmptyMessage(MESSAGE_DISABLE_REGISTRATION);
			}
		}
	}

	private class RegisterThread extends Thread {

		private Context context;

		public RegisterThread(Context context) {
			// TODO Auto-generated constructor stub
			this.context = context;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			// super.run();
			handler.sendEmptyMessage(MESSAGE_SHOW_DIALOG);

			Device device = new Device(context);
			String model = device.getModel();
			String imei = device.getIMEI();
			String imeiSv = device.getIMEISV();
			String serialNo = device.getSerialNumber();

			WifiConnection wifi = new WifiConnection(context);
			String wlanMac = wifi.getMacAddress();

			OperatingSystem os = new OperatingSystem();
			String osVersion = os.getVersion();

			RegisterDeviceSoap soap = new RegisterDeviceSoapImpl(context);
			int id = soap.registerDevice(model, imei, imeiSv, serialNo,
					wlanMac, osVersion);
			handler.sendEmptyMessage(MESSAGE_DISMISS_DIALOG);
			if (id > 0) {
				Message msg = handler.obtainMessage();
				msg.what = MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.register_device_success;
				handler.sendMessage(msg);
				
				handler.sendEmptyMessage(MESSAGE_DISABLE_REGISTRATION);
				
				String deviceStatus = getString(R.string.registered);
				String deviceId = Integer.toString(id);
				Map<String, String> data = new HashMap<String, String>();
				data.put(DEVICE_STATUS, deviceStatus);
				data.put(DEVICE_ID, deviceId);
				data.put(MODEL, model);
				data.put(IMEI, imei);
				data.put(IMEI_SV, imeiSv);
				data.put(SERIAL_NO, serialNo);
				data.put(WLAN_MAC, wlanMac);
				data.put(OS_VERSION, osVersion);
				msg = handler.obtainMessage();
				msg.what = MESSAGE_LOAD_STATUS;
				msg.obj = data;
				handler.sendMessage(msg);

				DeviceSettings settings = new DeviceSettings(context);
				settings.setDeviceId(id);
			} else {
				int code = id;
				Message msg = null;
				switch (code) {
				case ErrorCode.INTERNAL_ERROR:
					msg = handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.internal_error;
					handler.sendMessage(msg);
					break;

				case ErrorCode.UNKNOW_ERROR:
					msg = handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.unknow_error;
					handler.sendMessage(msg);
					break;

				case ErrorCode.RegisterDevice.NULL_IMEI:
					msg = handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.null_imei;
					handler.sendMessage(msg);
					break;

				case ErrorCode.RegisterDevice.INVALID_IMEI:
					msg = handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.invalid_imei;
					handler.sendMessage(msg);
					break;

				case ErrorCode.RegisterDevice.INVALID_IMEI_SV:
					msg = handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.invalid_imei_sv;
					handler.sendMessage(msg);
					break;

				case ErrorCode.RegisterDevice.INVALID_WLAN_MAC:
					msg = handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.invalid_wlan_mac;
					handler.sendMessage(msg);
					break;

				case ErrorCode.RegisterDevice.ALREADY_REGISTERED:
					msg = handler.obtainMessage();
					msg.what = MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.already_registered;
					handler.sendMessage(msg);
					break;

				default:
					break;
				}
			}
		}
	}
}
